<?php
/**
 * Created by PhpStorm.
 * （商家接口基类）
 * User: caicm
 * Date: 2017/6/14
 * Time: 16:27
 */

namespace WMApi\Controller;

use Think\Controller;
use WMApi\Model\WmSellerModel;
use WMApi\Model\WmStoreModel;

class SellerBaseController extends Controller {

    public $seller_id = 0;
    public $store_id = 0;

    protected function _initialize(){
        header("Access-Control-Allow-Origin: *");
        $this->seller_id = I('post.seller_id', 0, 'int');
        $this->store_id = I('post.store_id', 0, 'int');
        $controller_array = C('no_validation_controller');      //不验证的控制器
        $action_array = C('no_validation_action');              //不验证的方法

        if(!in_array(CONTROLLER_NAME, $controller_array) && !in_array(ACTION_NAME, $action_array)){
            // 验证Token   是否验证：1-是 0否（线上必须打开签名验证）
            if($_SERVER['HTTP_HOST'] == 'api.shidexian.com' || $_SERVER['HTTP_HOST'] == 'apitest.shidexian.com'){
                $is_check_token = 1;
            }else{
                $is_check_token = 0;
            }
            $this->_checkToken($is_check_token);
        }

        if(!empty($this->seller_id) && !empty($this->store_id)){

            $store_model = new WmStoreModel();

            //验证店铺信息
            if(!$store_model->find_store_num($this->seller_id, $this->store_id)){
                returnApiError('参数有误');
            }

        }

    }

    /**
     * 验证Token
     * Created By caicm
     * @param int $is_check 是否验证签名 1-是 0否
     * @return bool
     */
    protected function _checkToken($is_check=1){
        $sign = I('post.sign');
        if(empty($this->seller_id)){
            returnApiError('seller_id is null ！！！');
        }

        //获取签名
        $token = $this->get_token($this->seller_id);



        //验证签名
        if($is_check){

            $app_time = I('post.app_time');
            if(empty($app_time)){
                returnApiError('app_time is null');
            }
            //有效时间：30分钟
            if($app_time < time()-1800){
                //returnApiError('请求超时！');
            }

            //组装签名
            $app_sign = md5($this->seller_id . $token . $app_time . get_app_key());

            if($app_sign != $sign){
                returnApiError('签名有误！');
            }
        }

        return true;

    }


    /**
     * 获取商家token
     * Created By caicm
     * @param int $seller_id
     * @return mixed
     */
    protected function get_token($seller_id=0){
        $key = 'seller_token_'.$seller_id;
        $token = S($key);
        if(empty($token)){
            $seller_model = new WmSellerModel();
            $seller_info = $seller_model->find_seller_info($seller_id);
            if(!$seller_info){
                returnApiError('信息有误！！');
            }
            $token = $seller_info['seller_token'];
            S($key, $token, 86400); //缓存时间1天
        }

        if(!$token){
            returnApiError('信息有误！');
        }

        return $token;

    }



}